# -*- coding: utf-8 -*-
import functools
from flask import redirect, request, jsonify
from flask import session


def wraper_need_login(call_function):
	"""
	装饰器：判断用户是否已经登录系统n
	:param call_function:装饰的方法对象\n
	:return 执行方法 或者 直接跳转到登录页\n
	"""
	# 装饰器要使用functools.wraps的理由：
	# http://blog.csdn.net/tiwoo/article/details/50835337
	# https://segmentfault.com/a/1190000006658289
	@functools.wraps(call_function)
	def login_checker(*args, **kwargs):
		if not session.get('login_user'):
			if "application/json" == request.content_type:
				result = {"status": "error", "message": "未登录，请重新登录系统！"}
				return jsonify(result)
			else:
				return redirect('face_recognition/login.html')
		return call_function(*args, **kwargs)
	return login_checker


def wraper_json_data(call_function):
	"""
	装饰器：判断请求Content-Type是否为application/json\n
	:param call_function:装饰的方法对象\n
	:return 执行方法 或者 返回错误信息\n
	"""
	# 装饰器要使用functools.wraps的理由：
	# http://blog.csdn.net/tiwoo/article/details/50835337
	# https://segmentfault.com/a/1190000006658289
	@functools.wraps(call_function)
	def inner(*args, **kwargs):
		if not request.headers['Content-Type'] == 'application/json':
			result = {"status": "error", "message": "请求的数据格式'Content-Type'不正确，格式要求：application/json."}
			return jsonify(result)
		return call_function(*args, **kwargs)
	return inner
